package br.cin.ufpe.corba.iiop;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class MessageHeader {
		
	private static final String magic = "GIOP";
	private static final byte major = 1;
	private static final byte minor = 0;
	private static final boolean byte_order = true;
	
	private MsgType message_type;
	
	public MessageHeader(MsgType type) {
		this.message_type = type;
	}
		
	public MsgType getMessageType() {
		return message_type;
	}

	public void setMessageType(MsgType message_type) {
		this.message_type = message_type;
	}

	public void write(OutputStream out) throws IOException {
		DataOutputStream dos = new DataOutputStream(out);
		dos.writeBytes(magic);
		dos.writeByte(major);
		dos.writeByte(minor);
		dos.writeBoolean(byte_order);
		dos.writeByte(message_type.ordinal());
	}
	
	public static MessageHeader read(InputStream in) throws IOException {
		DataInputStream dis = new DataInputStream(in);
		
		for (int i = 0; i < magic.length(); i++) {
			if (magic.charAt(i) != dis.readByte()) {
				throw new IOException("Invalid GIOP Header");
			}
		}
		
		if (dis.readByte() != major) {
			throw new IOException("Invalid GIOP Major Version");
		}
		
		if (dis.readByte() != minor) {
			throw new IOException("Invalid GIOP Minor Version");
		}
		
		if (dis.readBoolean() != byte_order) {
			throw new IOException("Unsuported GIOP Byte Order");
		}
		
		MsgType type = MsgType.values()[dis.readByte()];
		
		return new MessageHeader(type);
	}
}
